<template>
  <div class="app-container">

    <div class="box ph-30">
      <div class="panel">
        <div class="panel-header">
          <h3 class="panel-title">填写报名信息</h3>
        </div>
        <div class="panel-body">
          <el-form ref="ruleFormRef" label-width="120px" class="signForm" :model="form" :rules="rules">
            <el-row>
              <el-col :span="8" :offset="2">
                <el-form-item label="照片" prop="picUrl">
                  <ImageUpload v-model="form.picUrl" class="threeFour" :limit="1" :is-show-tip="false"/>
                  <span class="tip"><i>*</i>请上传近期 彩色免冠照片</span>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="姓名" prop="realName">
                  <el-input v-model="form.realName" placeholder="请输入姓名"/>
                </el-form-item>

                <el-form-item label="证件类型" prop="idcType">
                  <el-select v-model="form.idcType" placeholder="请选择证件类型">
                    <el-option
                        v-for="item in certificates"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="证件号码" prop="idcCode">
                  <el-input v-model="form.idcCode" placeholder="请输入证件号码" @blur="checkCode"/>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="form.sex">
                    <el-radio label="1" size="large">男</el-radio>
                    <el-radio label="0" size="large">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birth">
                  <el-date-picker
                      v-model="form.birth"
                      type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                      placeholder="请选择出生日期"
                  />
                </el-form-item>

                <el-form-item label="联系方式" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入联系方式"/>
                </el-form-item>
                <el-form-item label="国籍" prop="countryId">
                  <el-select v-model="form.countryId" class="m-2" @change="changeCountryId">
                    <el-option v-for="item in countryList" :key="item.id" :label="item.name" :value="item.id"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="民族" prop="nation">
                  <el-select v-model="form.nation" style="width: 100%;">
                    <el-option
                        v-for="item in nationList"
                        :key="item.name"
                        :label="item.name"
                        :value="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-row v-if="participantsInfoArr&&participantsInfoArr.length>0">
            <el-col :span="16" :offset="4">
              <el-form label-width="120px">
                <h3>补充信息</h3>
                <el-form-item v-for="(s,index) in participantsInfoArr" :key="index">
                  <template #label>
                    <span v-if="s.status == 0" class="red">*</span>{{ s.name }}
                  </template>
                  <el-input v-if="s.type == '0'" v-model="s.value"/>
                  <el-input v-if="s.type == '1'" v-model="s.value" type="number"/>
                  <el-select v-if="s.type == '4'" v-model="s.value" class="m-2">
                    <el-option v-for="item in s.option" :key="item.id" :label="item.name" :value="item.name"/>
                  </el-select>
                  <ImageUpload
                      v-if="s.type == '3'" v-model="s.value" :limit="1"
                      :is-show-tip="false"
                  />
                  <!-- 文件 2-->
                  <FileUpload v-if="s.type == '2'" v-model="s.fixWxFile" :action="uploadUrl"/>

                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </div>
        <div class="panel-footer text-center">
          <el-button type="success" plain round @click="goPrev()">上一步</el-button>
          <el-button v-if="personId!='0'" type="success" round @click="goBack()">完成</el-button>
          <el-button v-else type="success" round @click="submitForm()">下一步</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { getCurrentInstance, onMounted } from '@vue/runtime-core'
import * as match from '@/api/match/pc'
import { toRefs } from '@vueuse/shared'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const uploadUrl = ref('/upload/upLoadToFileServer')
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
import { nationList } from '@/assets/js/data'

const data = reactive({
  form: {
    idcType: 0,
    countryId: 240,
    nation: '汉族'
  },
  rules: {
    // picUrl: { required: true, message: '请上传您的照片', trigger: 'blur' },
    // idcFrontImg: { required: true, message: '请上传身份证正面', trigger: 'blur' },
    // idcBackImg: { required: true, message: '请上传身份证反面', trigger: 'blur' },
    realName: { required: true, message: '请填写您的姓名', trigger: 'blur' },
    sex: { required: true, message: '请选择您的性别', trigger: 'change' },
    birth: { required: true, message: '请填写您的生日', trigger: 'blur' },
    idcType: { required: true, message: '请选择您的证件', trigger: 'change' },
    idcCode: { required: true, message: '请填写您的证件号', trigger: 'blur' }
    // phone: { required: true, message: '请填写您的联系方式', trigger: 'blur' }
  },
  certificates: [
    {
      value: '0',
      label: '居民身份证'
    },
    {
      value: '1',
      label: '护照'
    },
    {
      value: '2',
      label: '其他'
    }
  ],
  participantsInfoArr: [],
  noPhotoCanSign: '',
  countryList: [],
  personId: '0'
})
const {
  form, rules, certificates, participantsInfoArr, noPhotoCanSign, countryList, personId
} = toRefs(data)
let matchId = ''
let extraId = ''
onMounted(() => {
  const params = route.params
  const query = route.query
  matchId = params.id
  // 获取赛事详情
  init(matchId)
  getCountryList()
})
let coachOrLeaderFlag

function init(matchId) {
  match.getMatchById({ id: matchId }).then(res => {
    coachOrLeaderFlag = res.data.coachOrLeaderFlag
    noPhotoCanSign.value = res.data.noPhotoCanSign
    if (res.data.participantsInfo) {
      participantsInfoArr.value = JSON.parse(res.data.participantsInfo)
    }
    match.getMyPersonInfoWithcptId(matchId).then(res => {
      form.value = res.data
      if (res.data.cptPersonInfo?.personInfo) {
        // 补充字段信息
        participantsInfoArr.value = JSON.parse(form.value.cptPersonInfo.personInfo)
        for (var n of participantsInfoArr.value) {
          if (n.type == '3' && n.value.url) {
            // 图片
            n.value = n.value.url
          }
          if (n.type == '2') {
            // 文件
            var arr = [{
              name: n.value.name,
              url: n.value.url
            }]
            n.fixWxFile = arr
          }
        }
      }
    })
  })
}

function getCountryList() {
  match.countryList().then(res => {
    countryList.value = res.data
  })
}

function goBack() {
  let fileInfo = {}
  for (const n  of participantsInfoArr.value) {
    if (n.status == 0 && (!n.value && !n.fixWxFile)) {
      ElMessage.error('请完善必填字段')
      return
    }
    if (n.type == '2') {
      const temp = n.fixWxFile[0].name.split('.')
      fileInfo = {
        url: n.fixWxFile[0].url,
        name: n.fixWxFile[0].name,
        extname: temp[temp.length - 1]
      }
      n.value = fileInfo
    }
  }
  let obj = {}
  if (extraId != '0') { // 修改
    obj = {
      cptId: matchId,
      personId: form.value.id,
      id: extraId,
      personInfo: JSON.stringify(participantsInfoArr.value)
    }
  } else { // 没填过
    obj = {
      cptId: matchId,
      personId: form.value.id,
      personInfo: JSON.stringify(participantsInfoArr.value)
    }
  }
  match.saveSupplementInfo(obj).then(res => {
    // 返回
    router.go(-1)
  })
}

function goPrev() {
  router.go(-1)
}

function changeCountryId() {
  if (form.value.countryId != 240) {
    form.value.nation = '其他'
  }
}

function checkCode() {
  if (form.value.idcType == 0 && form.value.idcCode) {

    if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(form.value.idcCode))) {
      ElMessage.error('请输入正确的身份证号码')
    } else {
      let tmpStr = ''
      if (form.value.idcCode.length == 15) {
        tmpStr = form.value.idcCode.substring(6, 12)
        tmpStr = '19' + tmpStr
        tmpStr = tmpStr.substring(0, 4) + '-' + tmpStr.substring(4, 6) + '-' + tmpStr.substring(6)
      } else {
        tmpStr = form.value.idcCode.substring(6, 14)
        tmpStr = tmpStr.substring(0, 4) + '-' + tmpStr.substring(4, 6) + '-' + tmpStr.substring(6)
      }
      form.value.birth = tmpStr

      const res = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/
      if (form.value.idcCode && res.test(form.value.idcCode)) {
        const genderCode = form.value.idcCode.charAt(16)
        if (parseInt(genderCode) % 2 == 0) {
          form.value.sex = '0'
        } else {
          form.value.sex = '1'
        }
      }
    }
  }
}

function submitForm() {
  proxy.$refs['ruleFormRef'].validate((valid, fields) => {
    if (valid) {
      // var pattern = /^1[345789]\d{9}$/
      // if (!pattern.test(form.value.phone)) {
      //   ElMessage.error('请输入正确的手机号')
      //   return
      // }
      if (form.value.idcType == 0 && !(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(form.value.idcCode))) {
        ElMessage.error('请输入正确的身份证号码')
        return
      }
      // 验证补充信息必填
      for (const n of participantsInfoArr.value) {
        if (n.status == 0 && (!n.value && !n.fixWxFile)) {
          ElMessage.error(`请完善${n.name}信息`)
          return
        }
      }
      if (participantsInfoArr.value) {
        let fileInfo = {}
        for (var p of participantsInfoArr.value) {
          if (p.type == '2'&& p.fixWxFile) {
            const temp = p.fixWxFile[0].name.split('.')
            fileInfo = {
              url: p.fixWxFile[0].url,
              name: p.fixWxFile[0].name,
              extname: temp[temp.length - 1]
            }
            p.value = fileInfo
          }
        }
      }


      let obj = {}
      if (form.value.cptPersonInfo == null) {
        obj = {
          cptId: matchId,
          personId: form.value.id,
          personInfo: JSON.stringify(participantsInfoArr.value)
        }
      } else {
        obj = {
          cptId: matchId,
          id: form.value.cptPersonInfo.id,
          personId: form.value.id,
          personInfo: JSON.stringify(participantsInfoArr.value)
        }
      }
      form.value.label = '0'
      match.saveMyBaseInfo(form.value).then(res => {
        obj.personId = res.data
        match.saveSupplementInfo(obj).then(res2 => {
          if (coachOrLeaderFlag == '0') {
            // 不选教练 去选项目
            router.push({
              path: `chooseProject`,
              query: {
                matchId: matchId
              }
            })
          } else {
            router.push({
              path: `chooseCoach`,
              query: {
                matchId: matchId,
                signType: '0'
              }
            })
          }
        })
      })
    } else {
      console.log(form.value, fields)
    }
  })
}

</script>

<style scoped lang="scss">
.app-container {
  padding: 0;
  background: #F5F7F9;
}

.panel-footer .el-button--success {
  padding: 0 40px;
}

.signForm {
  .el-form-item__label {
    color: #4C5359;
  }
}

.tip {
  font-size: 13px;
  color: #999;
  margin: 10px 0;

  i {
    color: red;
    margin: 0 4px 0 0;
  }
}

.threeFour {
  width: 100%;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 160px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 160px;
}

.red {
  color: #f56c6c;
}
</style>
